package com.zhoutao123.hephaestus.service.impl;

import com.github.pagehelper.Page;
import com.zhoutao123.hephaestus.object.bussiness.VBlogComment;
import com.zhoutao123.hephaestus.object.exception.NotFountException;
import com.zhoutao123.hephaestus.object.transport.BlogCommentTO;
import com.zhoutao123.hephaestus.object.transport.PageBean;
import com.zhoutao123.hephaestus.repository.entity.BlogComment;
import com.zhoutao123.hephaestus.service.AbstractService;
import com.zhoutao123.hephaestus.service.BlogCommentService;
import com.zhoutao123.hephaestus.service.BlogService;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BlogCommentServiceImpl extends AbstractService implements BlogCommentService {

  @Autowired
  private BlogService blogService;

  @Override
  public VBlogComment add(BlogCommentTO blogCommentTO, UserAgent userAgent) {
    BlogComment blogComment = blogCommentTO.toEntity(userAgent);
    blogCommentRepo.insertSelective(blogComment);
    return getById(blogComment.getId());
  }

  public VBlogComment getById(String commentId) {

    BlogComment comment =
            blogCommentRepo
                    .selectOne(criteria -> criteria.andIdEqualTo(commentId))
                    .orElseThrow(() -> new NotFountException("获取失败，评论资源没有发现"));
    return VBlogComment.of(comment);
  }

  @Override
  public List<VBlogComment> getLatestComment(int number) {
    PageBean pageInfo = new PageBean();
    pageInfo.setPageNum(1).setPageSize(number);
    Page<BlogComment> blogComments =
            blogCommentRepo.selectListWithPageInfo(
                    criteria -> {
                    },
                    1,
                    number,
                    example -> {
                      example.setOrderByClause("create_time desc");
                    });
    return blogComments
            .stream()
            .map(VBlogComment::of)
            .map(
                    vBlogComment ->
                            vBlogComment.setBlog(blogService.getById(vBlogComment.getBlogId(), false)))
            .collect(Collectors.toList());
  }
}
